package homework013;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Send implements Runnable {

    private String host;
    private Integer port;

    Send(String host, Integer port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public void run() {
        System.out.println("请输入账号");
        Scanner scanner = new Scanner(System.in);
        String userName = scanner.nextLine();
        System.out.println("欢迎你" + userName + "，可以开始聊天");

        Socket socket = null;
        try {
            socket = new Socket(host, port);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        while (true) {
            // 和接收端约定，每次聊天以&结尾
            // 所以每次发送要强制加上这个字符
            String content = userName + ":" + scanner.nextLine();
            System.out.println(content);
            OutputStream os = null;
            try {
                os = socket.getOutputStream();
                os.write(content.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
